package cn.itcast.controller.log;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.apache.http.HttpRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

public class AspectLog {
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        SysLog sysLog = new SysLog();
        User user = (User) session.getAttribute("loginUser");
        if(user!=null){
        sysLog.setCompanyId(user.getCompanyId());
        sysLog.setCompanyName(user.getCompanyName());
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setIp(request.getRemoteAddr());
        sysLog.setTime(new Date());
        sysLog.setUserName(user.getUserName());
        }
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        if (method.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping annotation = method.getAnnotation(RequestMapping.class);
            String name = annotation.name();
            sysLog.setAction(name);
        }
        sysLog.setMethod(method.getName());
        sysLogService.save(sysLog);
        return pjp.proceed();
    }
}
